import {Application} from "pinus";
import {FieldInfo, MysqlError, Pool, PoolConnection} from "mysql";
import { reject, resolve } from "bluebird";
import Bluebird = require("bluebird");


export class Dao {
    protected pool: Pool
    protected insert = this.query
    protected delete = this.query
    protected update = this.query
    protected select = this.query

    public constructor(protected app: Application) {
        this.pool = app.get('MysqlPool')
    }

    private async query(sql: string, args: any[], connection?: PoolConnection) {
        return new Promise<{results?: any, fields?: FieldInfo[]}>((resolve, reject) => {
            const _connection = connection ? connection : this.pool
            _connection.query(sql, args, (err: MysqlError | null, results?: any, fields?: FieldInfo[]) => {
                if (err) {
                    reject(err)
                }
                resolve({results, fields})
            })
        })
    }
    protected async getConnection(): Promise<PoolConnection> {
        return new Promise((resolve, reject) => {
            this.pool.getConnection((err: MysqlError, connection: PoolConnection) => {
                if(!!err) {
                    reject(err)
                } else {
                    resolve(connection)
                }
            })
        })
    }

    protected async beginTransaction(connection: PoolConnection) {
        return new Promise((resolve, reject) => {
            connection.beginTransaction((err: MysqlError) => {
                if(!!err) {
                    reject(err)
                } else {
                    resolve(true)
                }
            })
        })
    }

    protected async rollback(connection: PoolConnection) {
        return new Promise((resolve, reject) => {
            connection.rollback((err: MysqlError) => {
                if(!!err) {
                    reject(err)
                } else {
                    resolve(true)
                }
            })
        })
    }

    protected async commit(connection: PoolConnection) {
        return new Promise((resolve, reject) => {
            connection.commit((err: MysqlError) => {
                if(!!err) {
                    reject(err)
                } else {
                    resolve(true)
                }
            })
        })
    }
}
